package com.is.common.exception;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.NetworkOnMainThreadException;
import android.widget.Toast;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

/**
 * 异常处理类
 * @author Administrator
 * @date 2017/4/6 0006
 */

public class ExceptionHandler extends Exception implements IExceptionHandler{
    private Context context;


    private ExceptionSender exceptionSender;

    public ExceptionHandler(Context context)
    {
        this.context = context;
        exceptionSender = new ExceptionSender(context);
    }
    @Override
    public String handlerException(Throwable exception, SQLiteDatabase db) {
        String message = "";
        if (exception instanceof ConnectException)
        {
            message = "网络连接有问题!";
        }
        else if (exception instanceof SocketTimeoutException)
        {
            message = "连接超时!";
        }
        else if (exception instanceof NullPointerException)
        {
            message = "程序出错，空指针错误!";
        }
        else if (exception instanceof IllegalArgumentException)
        {
            message = "程序出错，错误的请求参数!";
        }
        else if (exception instanceof ArithmeticException)
        {
            message = "程序出错，数值计算出错!";
        }
        else if (exception instanceof NetworkOnMainThreadException)
        {
            message = "程序出错，网络请求放在主线程中运行!";
        }
        else if (exception instanceof IllegalStateException)
        {
            message = "程序出错，网络请求要放在主线程中运行!";
        }
        else if (exception instanceof IndexOutOfBoundsException)
        {
            message = "数组越界异常!";
        }
        else if (exception instanceof IOException)
        {
            message = "程序出错，IO错误!";
        }
        else
        {
            message = exception.getMessage();
        }
        showTipMessgae(message);
        LogToFileUtils.write(exception);
        return message;
    }

    @Override
    public String handlerException(Throwable t) {
        return handlerException(t,null);
    }

    @Override
    public void sendException(Throwable t) {
        exceptionSender.send(t);
    }

    @Override
    public void showTipMessgae(final String msg)
    {
        if (context != null)
        {
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }
    }
}
